package org.jdcenter.rmi.impl;

import java.net.*;
import java.rmi.registry.Registry;

public class NamingURL {
    private String host;
    private int port;
    private String name;

    private NamingURL(String host, int port, String name) {
        this.host = host;
        this.port = port;
        this.name = name;
    }

    public static NamingURL parseURL(String str) throws MalformedURLException {
        try {
            URI uri = new URI(str);
            if(uri.getFragment() != null) {
                throw new MalformedURLException("invalid character, '#', in URL name: " + str);
            } else if(uri.getQuery() != null) {
                throw new MalformedURLException("invalid character, '?', in URL name: " + str);
            } else if(uri.getUserInfo() != null) {
                throw new MalformedURLException("invalid character, '@@', in URL host: " + str);
            }
            String scheme = uri.getScheme();
            if(scheme != null && !scheme.equals("rmi")) {
                throw new MalformedURLException("invalid URL scheme: " + str);
            }

            String name = uri.getPath();
            if(name != null) {
                if(name.startsWith("/")) {
                    name = name.substring(1);
                }
                if(name.length() == 0) {
                    name = null;
                }
            }

            String host = uri.getHost();
            if(host == null) {
                host = "";
                if(uri.getPort() == -1) {
                    // handle URIs with explicit port but no host (e.g., "//:1098/foo");
                    String authority = uri.getAuthority();
                    if(authority != null && authority.startsWith(":")) {
                        authority = "localhost" + authority;
                        uri = new URI(null, authority, null, null, null);
                    }
                }
            }

            int port = uri.getPort();
            if(port == -1) {
                port = Registry.REGISTRY_PORT;
            }
            return new NamingURL(host, port, name);

        } catch(URISyntaxException ex) {
            throw (MalformedURLException) new MalformedURLException("invalid URL string: " + str).initCause(ex);
        }
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public String getName() {
        return name;
    }

    public boolean isLocalHost() {
        if(host == null)
            return true;
        if(host.equalsIgnoreCase("localhost"))
            return true;
        if(host.equals("127.0.0.1"))
            return true;

        return false;
    }
}

